package org.file_service.service.serviceimpl;

import org.file_service.Analysis;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;

import org.file_service.dao.HistoryMapper;
import org.file_service.lang.Result;
import org.file_service.service.GenerateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.*;
import java.util.*;

@Slf4j
@Service
public class GenerateServiceImp implements GenerateService {

    @Autowired
    private HistoryMapper historyMapper;

    @Autowired
    FileSystem fileSystem;

    static Random random = new Random();
    static List<String> chaoxianglist = Arrays.asList("东南", "东西", "东北", "南北", "西南", "西北");
    static List<String> decorationlist = Arrays.asList("精装", "简装", "毛坯", "其他");
    static List<String> loucenglist = Arrays.asList("高楼层", "中楼层", "低楼层");
    static List <String[]> list1 = new ArrayList<>();
    static List <String[]> list2 = new ArrayList<>();
    static List <String[]> list3 = new ArrayList<>();
    static List <String[]> list4 = new ArrayList<>();
    static List <String[]> list5 = new ArrayList<>();
    static String localpath = "E:/zz/clean.csv";
    static String filePath = "/install/clean.csv";//文件路径
    static {
        String line = "";
        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            while ((line = br.readLine()) != null) {
                // use comma as separator
                String[] row = line.split(",");
                String zone = row[row.length-1];
                if (zone.equals("所属区")){
                    continue;
                }
                switch (zone) {
                    case "徐汇":
                        list1.add(row);
                        break;
                    case "普陀":
                        list2.add(row);
                        break;
                    case "浦东":
                        list3.add(row);
                        break;
                    case "闵行":
                        list4.add(row);
                        break;
                    default:
                        list5.add(row);
                        break;
                }

            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public Result DataGenerate(int userId, String operator, int times, String district, String rate) {
        System.out.println(list1.toString());
        long startTime = System.currentTimeMillis(); //获取开始时间
        String[] proportion = rate.split(",");
        double sum = 0;
        for (String e : proportion) {
            sum += Integer.parseInt(e);
        }
        System.out.println("比例和："+sum);
        String[] zone = district.split(",");
        String tmp = "";
        String outputPath = "/install/tmp/"+"result"+RandomStringUtils.random(6, "ab68efgh456fe")+".csv";
        try {
            BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(outputPath));
            long t = 0;
            for(int s = 0; s < proportion.length; s++) {
                for (int i = 0; i < (Double.parseDouble(proportion[s]) / sum) * times; i++) {
                    t++;
                    String zone_aim = zone[s];
                    List<String[]> record_aim = new ArrayList<>();
                    switch (zone_aim) {
                        case "徐汇":
                            record_aim = list1;
                            break;
                        case "普陀":
                            record_aim = list2;
                            break;
                        case "浦东":
                            record_aim = list3;
                            break;
                        case "闵行":
                            record_aim = list4;
                            break;
                        case "宝山":
                            record_aim = list5;
                            break;
                    }
                    String[] d = (String[]) record_aim.get(random.nextInt(record_aim.size()));
                    double mianji = random.nextInt(3) - 1.23 + Double.parseDouble(d[4]);
                    int danjia = random.nextInt(1600) - 887 + Integer.parseInt(d[6]);
                    int zongjia = (int) Math.round(danjia * mianji) / 10000 + 1;
                    int chengjiaoqi = Integer.parseInt(d[8]);
                    tmp =  t+ "" + ","
                            + d[1] + ","
                            + d[2] + ","
                            + d[3] + ","
                            + String.format("%.2f", mianji) + ","
                            + zongjia + ","
                            + danjia + ","
                            + (zongjia + random.nextInt(10)) + ","
                            + (chengjiaoqi + random.nextInt(2) - 1) + ","
                            + chaoxianglist.get(random.nextInt(chaoxianglist.size())) + ","
                            + decorationlist.get(random.nextInt(decorationlist.size())) + ","
                            + loucenglist.get(random.nextInt(loucenglist.size())) + ","
                            + d[12] + ","
                            + zone_aim;
                    bufferedWriter.write(tmp);
                    bufferedWriter.newLine();
                }
            }
            bufferedWriter.flush();
            bufferedWriter.close();
        } catch (IOException e) {
            System.out.println("文件读出错误");
        }
        int i = historyMapper.addRecord(operator, times, district + "-" + rate, userId);
        if (i !=0 ){
            int p = historyMapper.maxHistoryId();
            try {
                Thread.sleep(22000);

                reName("/zz/tmp", "/zz/analysis");

                Thread.sleep(5000);

                Analysis.analysis(p, userId);

                reName("/zz/analysis", "/zz/test."+RandomStringUtils.random(15, "abcdefghfrb452e32423131"));       //换文件名字


            } catch (InterruptedException  e) {
                e.printStackTrace();
            }
            long endTime = System.currentTimeMillis();    //获取结束时间
            String msg = p + ",程序运行时间：" + (endTime - startTime) + "ms";
            return Result.suc("生成数据+spark分析," + msg);
        }
        return Result.fail("生成数据失败");
    }

    public void reName(String oldPath, String newPath){
        try {
            fileSystem.rename(new Path(oldPath), new Path(newPath));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
